package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //定义不需要拦截的资源
        String[] urls ={
                "/employee/login",
                "/backend/**",
                "/front/**"
        };

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        log.info("本次请求的uri为："+requestURI);

        //判断是否有不需要拦截的请求
        boolean check = check(urls, requestURI);

        //如果有则放行
        if (check){
            log.info("本次请求不需要拦截");
            filterChain.doFilter(request, response);
            return;
        }

        //如果没有，则说明此次请求需要访问站内资源
        //判断用户是否登录
        Object employee = request.getSession().getAttribute("employee");
        if (employee!=null){
            log.info("用户已登录，id为{}"+employee);
            filterChain.doFilter(request, response);
            return;
        }

        //到此处仍未放行，则说明有未登录用户要访问站内资源，拦截并返回信息给前端
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        //将前端请求的uri与配置好的路径进行匹配，如果能匹配到的话，则放行
        for (String url:urls){
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;

    }
}
